package com.framework.loippi.service.weixin.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.utils.AesCbcUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.framework.loippi.entity.weixin.WxUserJson;
import com.framework.loippi.service.weixin.AES;
import com.framework.loippi.service.weixin.WxUserService;
import com.google.gson.Gson;

@Service("wxUserService")
public class WxUserServiceImpl extends WxBaseServiceImpl implements WxUserService{
	
	static{
		Security.addProvider(new BouncyCastleProvider()); 
	}

	@Override
	public String handleMessage(Element root) {
		// TODO Auto-generated method stub
		return null;
	}
	/**
	 * 获取openId
	 */
	@Override
	public WxUserJson getUserWxNum(String code) {
		if(code == null || code.equals("")){
			return null;
		}
		WxUserJson wu = this.getUserAccessTokenByCode(code);
		return wu;
	}

	@Override
	public WxUserJson getUSerWXNumForApplet(String code) {
		if(code == null || code.equals("")){
			return null;
		}
		WxUserJson wu = this.getUserAccessTokenByCodeForAppLet(code);
		return wu;
	}

	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 */
	public WxUserJson getUserAccessTokenByCode(String code){
		String result= null;
		WxUserJson wxuser = new WxUserJson();
		HttpClient client = new HttpClient();
//		String resultStr = this.USERACCESSTOKEN_URL;
		String resultStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ConfigCache.getConfig("wx.mp.appId")+"&secret="+ConfigCache.getConfig("wx.mp.secret")+"&code=CODE&grant_type=authorization_code";
		String string = resultStr.replace("CODE", code);
		HttpMethod method=new GetMethod(string);
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			
			Gson gs = new Gson();
			wxuser = gs.fromJson(result, WxUserJson.class);
			
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wxuser;
	}


	/**
	 * 获取AccessToken
	 * @param code
	 * @return
	 */
	public WxUserJson getUserAccessTokenByCodeForAppLet(String code){
		String result= null;
		WxUserJson wxuser = new WxUserJson();
		HttpClient client = new HttpClient();
		String resultStr = String.format(this.APPLETACCESSTOKEN_URL, ConfigCache.getConfig("wx.ma.appId"),ConfigCache.getConfig("wx.ma.secret"));
		String string = resultStr.replace("CODE", code);
		HttpMethod method=new GetMethod(string);
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
			method.releaseConnection();
			System.out.println(result);
			Gson gs = new Gson();
			wxuser = gs.fromJson(result, WxUserJson.class);

		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wxuser;
	}
	
	
	/**
     * 解密用户敏感数据获取用户信息
     * 
     * @author zhy
     * @param sessionKey 数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv 加密算法的初始向量
     * @return
     */
    @SuppressWarnings("static-access")
	public JSONObject getUserInfo(String encryptedData,String sessionKey,String iv){
		String s = null;
		try {
			s = AesCbcUtils.decrypt(encryptedData, sessionKey, iv, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.parseObject(s);
    }
    

    
}
